package top.jfunc.websocket.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPubSub;
import top.jfunc.json.impl.JSONObject;
import top.jfunc.websocket.WebSocketManager;
import top.jfunc.websocket.WebSocketManagerUtil;
import top.jfunc.websocket.redis.action.Action;
import top.jfunc.websocket.redis.action.ActionFactory;

import java.util.concurrent.CountDownLatch;

import static top.jfunc.websocket.redis.action.Action.ACTION;

public class Subscriber extends JedisPubSub {
    private static final Logger LOGGER = LoggerFactory.getLogger(Subscriber.class);

    private CountDownLatch latch;
    public Subscriber(){}
    public Subscriber(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void onMessage(String channel, String message) {       //收到消息会调用
        System.out.println(String.format("receive redis published message, channel %s, message %s", channel, message));
        LOGGER.info(message);

        JSONObject object = new JSONObject(message);
        if(!object.containsKey(ACTION)){
            return;
        }
        String actionName = object.getString(ACTION);
        Action action = getAction(actionName);
        action.doMessage(getWebSocketManager() , object);

        if(null != latch){
            latch.countDown();
        }
    }
    @Override
    public void onSubscribe(String channel, int subscribedChannels) {    //订阅了频道会调用
        LOGGER.info(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
                channel, subscribedChannels));
    }
    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {   //取消订阅 会调用
        LOGGER.info(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
                channel, subscribedChannels));
    }

    protected Action getAction(String actionName) {
        return ActionFactory.getAction(actionName);
    }
    protected WebSocketManager getWebSocketManager() {
        return WebSocketManagerUtil.getWebSocketManager();
    }
}